重载运算符时,前置运算符需要在“func”关键字前添加“prefix”关键字:
1234567891011121314151617struct Vector2D {var x = 0.0var y = 0.0}func +(left: Vector2D, right: Vector2D) -> Vector2D {return Vector2D(x: left.x + right.x, y: left.y + right.y)}// 这里是前置运算符重载,需要添加“prefix”标识prefix func -(origin: Vector2D) -> Vector2D {return Vector2D(x: -origin.x, y: -origin.y)}let vec1 = Vector2D(x: 2, y: 3)let vec2 = Vector2D(x: 1, y: 4)let vec3 = vec1 + vec2let vec4 = -vec1
> 此外,“infix”为中置操作符(如+、-、*、/等两边都需要操作数的);“postfix”为后置操作符;当然,“prefix”为前置操作符。